package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.anno.LogOperation;
import org.example.pojo.Dept;
import org.example.pojo.Emp;
import org.example.pojo.Result;
import org.example.service.DeptService;
import org.example.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
public class DeptController {
    @Autowired
    private DeptService deptService;
    @Autowired
    private EmpService empService;

    /**
     * 查询部门信息
     * @return
     */
    @GetMapping("/depts")
    public Result list(){
        log.info("查询部门列表");
        List<Dept> deptList = deptService.findAll();
        return Result.success(deptList);
    }

    /**
     * 删除部门
     * @param id
     * @return
     */
    @LogOperation
    @DeleteMapping("/depts")
    public Result delete(Integer id){
        log.info("根据id删除部门信息,id:{}",id);
        List<Emp> empList =empService.selectByDeptId(id);
        if (empList.size()>0&&empList!=null) {
            throw new RuntimeException("该部门下有员工，不能删除");
        } else {
            deptService.deleteById(id);
        }
        return Result.success();
    }

    /**
     * 添加部门
     * @param dept
     * @return
     */
    @LogOperation
    @PostMapping("/depts")
    public Result add(@RequestBody Dept dept){
        log.info("添加部门,dept:{}",dept);
        deptService.insert(dept);
        return Result.success();
    }

    /**
     * 修改部门信息
     * @param dept
     * @return
     */
    @LogOperation
    @PutMapping("/depts")
    public Result update(@RequestBody Dept dept){
        log.info("修改部门信息,dept:{}",dept);
        deptService.update(dept);
        return Result.success();
    }

    /**
     * 根据id查询部门信息
     * @param id
     * @return
     */
    @GetMapping("/depts/{id}")
    public Result findById(@PathVariable Integer id){
        log.info("根据id查询部门信息,id:{}",id);
        Dept dept=deptService.findById(id);
        return Result.success(dept);
    }
}
